package com.accloud.cloudservice;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.accloud.common.ACConfiguration;
import com.accloud.common.ACHelper;
import com.accloud.common.ACSignature;
import com.accloud.service.ACException;
import com.accloud.service.ACObject;
import com.accloud.service.ACPushMgr;
import com.accloud.service.ACPushReceive;
import com.accloud.service.ACPushTable;
import com.accloud.utils.ACUtils;
import com.accloud.utils.LogUtil;
import com.accloud.utils.PreferencesUtils;
import com.fasterxml.jackson.core.util.BufferRecycler;
import cz.msebera.android.httpclient.cookie.ClientCookie;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;

public class ACPushManager implements ACPushMgr {
    private static final int HEARTBEAT_PERIOD = 120000;
    private static final int HEARTBEAT_TIMEOUT = 180000;
    private static final int MAX_TIME = 16000;
    private static final int MSG_CONNECT_ERROR = -1;
    private static final int MSG_CONNECT_SUCCESS = 0;
    private static final int MSG_DATA = 1;
    private static final int MSG_HEARTBEAT = 3;
    private static final int MSG_REWATCHING = 2;
    public static final String TAG = ACPushManager.class.getSimpleName();
    private static final String VERSION = "1.1.0";
    private int TIME = BufferRecycler.DEFAULT_WRITE_CONCAT_BUFFER_LEN;
    WebSocketClient client;
    VoidCallback connectCallback;
    private boolean disconnect = false;
    Handler handler = new Handler(Looper.getMainLooper()) {
        /* class com.accloud.cloudservice.ACPushManager.AnonymousClass1 */

        @Override // android.os.Handler
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    if (ACPushManager.this.connectCallback != null) {
                        ACPushManager.this.connectCallback.error((ACException) msg.obj);
                    }
                    ACPushManager.this.connectCallback = null;
                    ACPushManager.this.disconnect();
                    return;
                case 0:
                    LogUtil.d(ACPushManager.TAG, "onConnect");
                    ACPushManager.this.loginWithSign();
                    return;
                case 1:
                    byte[] message = (byte[]) msg.obj;
                    ACObject resp = new ACObject();
                    try {
                        ACObjectMarshaller.unmarshal(resp, message);
                    } catch (IOException e) {
                    }
                    String name = resp.getString("name");
                    long errCode = resp.getLong("errCode");
                    String errMsg = resp.getString("errMsg");
                    String errDesc = resp.getString("errDesc");
                    long seqId = resp.getLong("seqId");
                    char c = 65535;
                    switch (name.hashCode()) {
                        case -1868559828:
                            if (name.equals("loginWithSign")) {
                                c = 0;
                                break;
                            }
                            break;
                        case -274141738:
                            if (name.equals("unwatch")) {
                                c = 2;
                                break;
                            }
                            break;
                        case 3076010:
                            if (name.equals("data")) {
                                c = 4;
                                break;
                            }
                            break;
                        case 112903375:
                            if (name.equals("watch")) {
                                c = 1;
                                break;
                            }
                            break;
                        case 200896764:
                            if (name.equals("heartbeat")) {
                                c = 5;
                                break;
                            }
                            break;
                        case 1100652156:
                            if (name.equals("rewatch")) {
                                c = 3;
                                break;
                            }
                            break;
                    }
                    switch (c) {
                        case 0:
                            if (errCode == 0) {
                                LogUtil.d(ACPushManager.TAG, seqId + ":loginWithSign success");
                                if (ACPushManager.this.connectCallback != null) {
                                    ACPushManager.this.connectCallback.success();
                                }
                                ACPushManager.this.connectCallback = null;
                                if (ACPushManager.this.syncCallbacks != null && ACPushManager.this.syncCallbacks.size() > 0) {
                                    for (VoidCallback callback : ACPushManager.this.syncCallbacks) {
                                        callback.success();
                                    }
                                    ACPushManager.this.syncCallbacks.clear();
                                }
                                ACPushManager.this.timestamp = System.currentTimeMillis();
                                ACPushManager.this.handler.sendEmptyMessageDelayed(3, 120000);
                                return;
                            } else if (errCode == 3515) {
                                LogUtil.d(ACPushManager.TAG, seqId + ":loginWithSign failed[" + errCode + "-->" + errMsg + "(" + errDesc + ")]");
                                new Thread(new Runnable() {
                                    /* class com.accloud.cloudservice.ACPushManager.AnonymousClass1.AnonymousClass1 */

                                    @Override // java.lang.Runnable
                                    public void run() {
                                        try {
                                            LogUtil.d(ACPushManager.TAG, "updateAccessToken");
                                            AC.accountMgr().updateAccessToken();
                                        } catch (ACException e) {
                                            ACPushManager.this.handler.obtainMessage(-1, e).sendToTarget();
                                        }
                                    }
                                }).start();
                                return;
                            } else {
                                LogUtil.d(ACPushManager.TAG, seqId + ":loginWithSign failed[" + errCode + "-->" + errMsg + "(" + errDesc + ")]");
                                if (ACPushManager.this.connectCallback != null) {
                                    ACPushManager.this.connectCallback.error(new ACException((int) errCode, errMsg, errDesc));
                                }
                                ACPushManager.this.connectCallback = null;
                                ACPushManager.this.disconnect();
                                return;
                            }
                        case 1:
                            if (errCode == 0) {
                                LogUtil.d(ACPushManager.TAG, seqId + ":watch success");
                                for (Integer num : ACPushManager.this.watchCallbacks.keySet()) {
                                    int key = num.intValue();
                                    if (seqId == ((long) key)) {
                                        ACPushManager.this.watchCallbacks.get(Integer.valueOf(key)).success();
                                    }
                                }
                                return;
                            }
                            LogUtil.d(ACPushManager.TAG, seqId + ":watch failed[" + errCode + "-->" + errMsg + "(" + errDesc + ")]");
                            for (Integer num2 : ACPushManager.this.watchCallbacks.keySet()) {
                                int key2 = num2.intValue();
                                if (seqId == ((long) key2)) {
                                    ACPushManager.this.watchCallbacks.get(Integer.valueOf(key2)).error(new ACException((int) errCode, errMsg, errDesc));
                                }
                            }
                            return;
                        case 2:
                            if (errCode == 0) {
                                LogUtil.d(ACPushManager.TAG, seqId + ":unwatch success");
                                for (Integer num3 : ACPushManager.this.unwatchCallbacks.keySet()) {
                                    int key3 = num3.intValue();
                                    if (seqId == ((long) key3)) {
                                        ACPushManager.this.unwatchCallbacks.get(Integer.valueOf(key3)).success();
                                    }
                                }
                                return;
                            }
                            LogUtil.d(ACPushManager.TAG, seqId + ":unwatch failed[" + errCode + "-->" + errMsg + "(" + errDesc + ")]");
                            for (Integer num4 : ACPushManager.this.unwatchCallbacks.keySet()) {
                                int key4 = num4.intValue();
                                if (seqId == ((long) key4)) {
                                    ACPushManager.this.unwatchCallbacks.get(Integer.valueOf(key4)).error(new ACException((int) errCode, errMsg, errDesc));
                                }
                            }
                            return;
                        case 3:
                            LogUtil.d(ACPushManager.TAG, seqId + ":cloud call me to rewatch");
                            synchronized (ACPushManager.this.lock) {
                                for (ACPushTable pushTable : ACPushManager.this.pushTables) {
                                    ACPushManager.this.rewatch(pushTable, new VoidCallback() {
                                        /* class com.accloud.cloudservice.ACPushManager.AnonymousClass1.AnonymousClass2 */

                                        @Override // com.accloud.cloudservice.VoidCallback
                                        public void success() {
                                            LogUtil.d(ACPushManager.TAG, "rewatch success");
                                        }

                                        @Override // com.accloud.cloudservice.BaseCallback
                                        public void error(ACException e) {
                                            LogUtil.d(ACPushManager.TAG, "rewatch failed:" + e.toString());
                                        }
                                    });
                                }
                            }
                            return;
                        case 4:
                            ACObject payload = resp.getACObject("payload");
                            LogUtil.d(ACPushManager.TAG, "receive:\n" + resp.toString());
                            String className = payload.getString("className");
                            int opType = payload.getInt("opType");
                            ACObject data = payload.getACObject("data");
                            AC.sEventManager.track(new ReceiveEvent(className, opType, data.toString()));
                            if (ACPushManager.this.receiver != null) {
                                ACPushManager.this.receiver.success(new ACPushReceive(className, (long) opType, data));
                                return;
                            }
                            return;
                        case 5:
                            LogUtil.d(ACPushManager.TAG, "receive heartbeat");
                            ACPushManager.this.timestamp = System.currentTimeMillis();
                            return;
                        default:
                            return;
                    }
                case 2:
                    LogUtil.d(ACPushManager.TAG, "rewatching");
                    ACPushManager.this.reConnect = true;
                    if (ACPushManager.this.connectCallback != null) {
                        ACPushManager.this.connect(ACPushManager.this.connectCallback);
                        return;
                    } else {
                        ACPushManager.this.connect(new VoidCallback() {
                            /* class com.accloud.cloudservice.ACPushManager.AnonymousClass1.AnonymousClass3 */

                            @Override // com.accloud.cloudservice.VoidCallback
                            public void success() {
                                synchronized (ACPushManager.this.lock) {
                                    for (ACPushTable pushTable : ACPushManager.this.pushTables) {
                                        ACPushManager.this.rewatch(pushTable, new VoidCallback() {
                                            /* class com.accloud.cloudservice.ACPushManager.AnonymousClass1.AnonymousClass3.AnonymousClass1 */

                                            @Override // com.accloud.cloudservice.VoidCallback
                                            public void success() {
                                                LogUtil.d(ACPushManager.TAG, "rewatch success");
                                            }

                                            @Override // com.accloud.cloudservice.BaseCallback
                                            public void error(ACException e) {
                                                LogUtil.d(ACPushManager.TAG, "rewatch failed:" + e.toString());
                                            }
                                        });
                                    }
                                }
                            }

                            @Override // com.accloud.cloudservice.BaseCallback
                            public void error(ACException e) {
                                LogUtil.d(ACPushManager.TAG, "connect failed:" + e.toString());
                            }
                        });
                        return;
                    }
                case 3:
                    if (System.currentTimeMillis() - ACPushManager.this.timestamp >= 180000) {
                        LogUtil.d(ACPushManager.TAG, "no receive heartbeat, close client[" + ACPushManager.this.isConnect + "] to reconnect...");
                        if (ACPushManager.this.isConnect) {
                            ACPushManager.this.client.close();
                            return;
                        }
                        return;
                    }
                    ACPushManager.this.heartbeat();
                    ACPushManager.this.handler.sendEmptyMessageDelayed(3, 120000);
                    return;
                default:
                    return;
            }
        }
    };
    private boolean isConnect = false;
    private boolean isReWatching = false;
    private final Object lock = new Object();
    private boolean onConnect = false;
    public List<ACPushTable> pushTables = new ArrayList();
    private boolean reConnect = false;
    PayloadCallback<ACPushReceive> receiver;
    public int seqId = 0;
    StatusEvent statusEvent;
    List<VoidCallback> syncCallbacks;
    private long timestamp = 0;
    Map<Integer, VoidCallback> unwatchCallbacks = new HashMap();
    Map<Integer, VoidCallback> watchCallbacks = new HashMap();

    @Override // com.accloud.service.ACPushMgr
    public synchronized void connect(VoidCallback connectCallback2) {
        VoidEventCallback callbackWrapper = new VoidEventCallback(new ConnectEvent(), connectCallback2);
        if (!AC.accountMgr().isLogin()) {
            if (callbackWrapper != null) {
                callbackWrapper.error(new ACException(ACException.NO_LOGIN, "no login"));
            }
        } else if (this.reConnect || ACUtils.isNetworkConnected()) {
            if (!this.onConnect || this.reConnect) {
                this.onConnect = true;
                LogUtil.d(TAG, "isConnect:" + this.isConnect + " isRewatching:" + this.isReWatching + " reconnect:" + this.reConnect);
                if ((this.isConnect || this.isReWatching) && !this.reConnect) {
                    LogUtil.d(TAG, "socket has been connected, return");
                    this.onConnect = false;
                    if (callbackWrapper != null) {
                        callbackWrapper.success();
                    }
                } else {
                    LogUtil.d(TAG, "connecting");
                    init();
                    this.client.connect();
                    this.connectCallback = callbackWrapper;
                }
                this.reConnect = false;
            } else {
                LogUtil.d(TAG, "socket now is connecting, wait until socket connected");
                if (this.syncCallbacks == null) {
                    this.syncCallbacks = new ArrayList();
                }
                if (callbackWrapper != null) {
                    this.syncCallbacks.add(callbackWrapper);
                }
            }
        } else if (callbackWrapper != null) {
            callbackWrapper.error(new ACException(ACException.NO_NETWORK_AVAILABLE, "no network available"));
        }
    }

    private void init() {
        try {
            this.disconnect = false;
            LogUtil.d(TAG, ACConfiguration.getAppGatewayAddr());
            this.client = new WebSocketClient(new URI(ACConfiguration.getAppGatewayAddr()), new Draft_17()) {
                /* class com.accloud.cloudservice.ACPushManager.AnonymousClass2 */

                @Override // org.java_websocket.client.WebSocketClient
                public void onOpen(ServerHandshake serverHandshake) {
                    LogUtil.d(ACPushManager.TAG, "onOpen");
                    if (ACPushManager.this.statusEvent != null) {
                        ACPushManager.this.statusEvent.onConnect();
                    }
                    ACPushManager.this.TIME = BufferRecycler.DEFAULT_WRITE_CONCAT_BUFFER_LEN;
                    ACPushManager.this.onConnect = false;
                    ACPushManager.this.isConnect = true;
                    ACPushManager.this.isReWatching = false;
                    try {
                        long currentTimeMillis = System.currentTimeMillis() + 5000;
                        long accessTokenExpire = PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_TOKEN_EXPIRE, 0);
                        long refreshTokenExpire = PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_REFRESH_TOKEN_EXPIRE, 0);
                        if (accessTokenExpire != 0 && accessTokenExpire < currentTimeMillis && refreshTokenExpire > currentTimeMillis) {
                            AC.accountMgr().updateAccessToken();
                        }
                        ACPushManager.this.handler.sendEmptyMessage(0);
                    } catch (ACException e) {
                        Message msg = ACPushManager.this.handler.obtainMessage();
                        msg.what = -1;
                        msg.obj = e;
                        ACPushManager.this.handler.sendMessage(msg);
                    }
                }

                @Override // org.java_websocket.client.WebSocketClient
                public void onMessage(String message) {
                    Message msg = ACPushManager.this.handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = message.getBytes();
                    ACPushManager.this.handler.sendMessage(msg);
                }

                @Override // org.java_websocket.client.WebSocketClient
                public void onMessage(ByteBuffer bytes) {
                    Message msg = ACPushManager.this.handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = bytes.array();
                    ACPushManager.this.handler.sendMessage(msg);
                }

                @Override // org.java_websocket.client.WebSocketClient
                public void onClose(int i, String s, boolean remote) {
                    LogUtil.d(ACPushManager.TAG, "onClose:" + s);
                    if (ACPushManager.this.statusEvent != null) {
                        ACPushManager.this.statusEvent.onDisconnect();
                    }
                    if (ACPushManager.this.isConnect) {
                        AC.sEventManager.track(new DisconnectEvent(i == 1000 && !remote ? null : new ACException(ACException.INTERNAL_ERROR)));
                    }
                    ACPushManager.this.isConnect = false;
                    if (!ACPushManager.this.disconnect) {
                        ACPushManager.this.isReWatching = true;
                    }
                    try {
                        Thread.sleep((long) ACPushManager.this.TIME);
                    } catch (InterruptedException e) {
                    }
                    if (!ACPushManager.this.disconnect) {
                        if (ACPushManager.this.TIME < ACPushManager.MAX_TIME) {
                            ACPushManager.this.TIME *= 2;
                        }
                        ACPushManager.this.handler.sendEmptyMessage(2);
                    }
                }

                @Override // org.java_websocket.client.WebSocketClient
                public void onError(Exception e) {
                    LogUtil.d(ACPushManager.TAG, "onError:" + e.getMessage());
                    if (ACPushManager.this.statusEvent != null) {
                        ACPushManager.this.statusEvent.onDisconnect();
                    }
                    ACPushManager.this.isConnect = false;
                    ACPushManager.this.isReWatching = true;
                    try {
                        Thread.sleep((long) ACPushManager.this.TIME);
                    } catch (InterruptedException e2) {
                    }
                    if (!ACPushManager.this.disconnect) {
                        if (ACPushManager.this.TIME < ACPushManager.MAX_TIME) {
                            ACPushManager.this.TIME *= 2;
                        }
                        ACPushManager.this.handler.sendEmptyMessage(2);
                    }
                }
            };
        } catch (URISyntaxException e) {
        }
    }

    public void loginWithSign() {
        LogUtil.d(TAG, this.seqId + ":loginWithSign");
        ACObject object = new ACObject();
        ACObject header = new ACObject();
        header.put("name", "loginWithSign");
        header.put("type", "json");
        header.put("ver", VERSION);
        int i = this.seqId;
        this.seqId = i + 1;
        header.put("seqId", Integer.valueOf(i));
        ACObject verifySign = new ACObject();
        ACSignature signature = new ACHelper().genSignature();
        verifySign.put(ClientCookie.DOMAIN_ATTR, AC.majorDomain);
        verifySign.put("userId", Long.valueOf(PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_USERID, 0)));
        verifySign.put("timestamp", Long.valueOf(signature.getTimestamp()));
        verifySign.put("timeout", Long.valueOf(signature.getTimeout()));
        verifySign.put("nonce", signature.getNonce());
        verifySign.put("sign", signature.getSignature());
        ACObject payload = new ACObject();
        payload.put("keepAlive", 120);
        object.put("header", header);
        object.put("verifySign", verifySign);
        object.put("payload", payload);
        try {
            this.client.send(ACObjectMarshaller.marshal(object));
        } catch (Exception e) {
        }
    }

    @Override // com.accloud.service.ACPushMgr
    public synchronized void watch(ACPushTable table, VoidCallback callback) {
        if (this.isConnect || this.isReWatching) {
            LogUtil.d(TAG, this.seqId + ":watch---className[" + table.getClassName() + "], primaryKey[" + table.getPrimaryKey().toString() + "]");
            synchronized (this.lock) {
                this.pushTables.add(table);
            }
            this.watchCallbacks.put(Integer.valueOf(this.seqId), new VoidEventCallback(new WatchEvent(table), callback));
            ACObject object = new ACObject();
            ACObject header = new ACObject();
            header.put("name", "watch");
            header.put("type", "json");
            header.put("ver", VERSION);
            int i = this.seqId;
            this.seqId = i + 1;
            header.put("seqId", Integer.valueOf(i));
            object.put("header", header);
            ACObject payload = new ACObject();
            payload.put("className", table.getClassName());
            payload.put("primaryKey", table.getPrimaryKey());
            payload.put("opType", Integer.valueOf(table.getOpType()));
            object.put("payload", payload);
            ACObject verifySign = new ACObject();
            ACSignature signature = new ACHelper().genSignature();
            verifySign.put(ClientCookie.DOMAIN_ATTR, AC.majorDomain);
            verifySign.put("userId", Long.valueOf(PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_USERID, 0)));
            verifySign.put("timestamp", Long.valueOf(signature.getTimestamp()));
            verifySign.put("timeout", Long.valueOf(signature.getTimeout()));
            verifySign.put("nonce", signature.getNonce());
            verifySign.put("sign", signature.getSignature());
            object.put("verifySign", verifySign);
            try {
                this.client.send(ACObjectMarshaller.marshal(object));
            } catch (Exception e) {
            }
        } else {
            callback.error(new ACException(ACException.CONNECTED_FIRST, "you should use connect first"));
        }
    }

    public void rewatch(ACPushTable table, VoidCallback callback) {
        LogUtil.d(TAG, this.seqId + ":rewatch");
        this.watchCallbacks.put(Integer.valueOf(this.seqId), new VoidEventCallback(new WatchEvent(table), callback));
        ACObject object = new ACObject();
        ACObject header = new ACObject();
        header.put("name", "watch");
        header.put("type", "json");
        header.put("ver", VERSION);
        int i = this.seqId;
        this.seqId = i + 1;
        header.put("seqId", Integer.valueOf(i));
        object.put("header", header);
        ACObject payload = new ACObject();
        payload.put("className", table.getClassName());
        payload.put("primaryKey", table.getPrimaryKey());
        payload.put("opType", Integer.valueOf(table.getOpType()));
        object.put("payload", payload);
        ACObject verifySign = new ACObject();
        ACSignature signature = new ACHelper().genSignature();
        verifySign.put(ClientCookie.DOMAIN_ATTR, AC.majorDomain);
        verifySign.put("userId", Long.valueOf(PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_USERID, 0)));
        verifySign.put("timestamp", Long.valueOf(signature.getTimestamp()));
        verifySign.put("timeout", Long.valueOf(signature.getTimeout()));
        verifySign.put("nonce", signature.getNonce());
        verifySign.put("sign", signature.getSignature());
        object.put("verifySign", verifySign);
        try {
            this.client.send(ACObjectMarshaller.marshal(object));
        } catch (Exception e) {
        }
    }

    @Override // com.accloud.service.ACPushMgr
    public synchronized void unwatch(ACPushTable table, VoidCallback callback) {
        int i = 0;
        while (i < this.pushTables.size()) {
            ACPushTable pushTable = this.pushTables.get(i);
            if (pushTable.equals(table)) {
                LogUtil.d(TAG, "remove className[" + table.getClassName() + "], payload[" + table.getPrimaryKey().toString() + "]");
                this.pushTables.remove(pushTable);
                i--;
            }
            i++;
        }
        if (!ACUtils.isNetworkConnected() || !this.isConnect) {
            callback.success();
        } else {
            LogUtil.d(TAG, this.seqId + ":unwatch");
            this.unwatchCallbacks.put(Integer.valueOf(this.seqId), new VoidEventCallback(new UnwatchEvent(table), callback));
            ACObject object = new ACObject();
            ACObject header = new ACObject();
            header.put("name", "unwatch");
            header.put("type", "json");
            header.put("ver", VERSION);
            int i2 = this.seqId;
            this.seqId = i2 + 1;
            header.put("seqId", Integer.valueOf(i2));
            object.put("header", header);
            ACObject payload = new ACObject();
            payload.put("className", table.getClassName());
            payload.put("primaryKey", table.getPrimaryKey());
            object.put("payload", payload);
            ACObject verifySign = new ACObject();
            ACSignature signature = new ACHelper().genSignature();
            verifySign.put(ClientCookie.DOMAIN_ATTR, AC.majorDomain);
            verifySign.put("userId", Long.valueOf(PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_USERID, 0)));
            verifySign.put("timestamp", Long.valueOf(signature.getTimestamp()));
            verifySign.put("timeout", Long.valueOf(signature.getTimeout()));
            verifySign.put("nonce", signature.getNonce());
            verifySign.put("sign", signature.getSignature());
            object.put("verifySign", verifySign);
            try {
                this.client.send(ACObjectMarshaller.marshal(object));
            } catch (Exception e) {
            }
        }
    }

    @Override // com.accloud.service.ACPushMgr
    public void unwatchAll() {
        LogUtil.d(TAG, "unwatchAll");
        synchronized (this.lock) {
            for (ACPushTable table : this.pushTables) {
                if (!(ACUtils.isNetworkConnected() && this.isConnect)) {
                    break;
                }
                LogUtil.d(TAG, this.seqId + ":unwatch, remove className[" + table.getClassName() + "], payload[" + table.getPrimaryKey().toString() + "]");
                ACObject object = new ACObject();
                ACObject header = new ACObject();
                header.put("name", "unwatch");
                header.put("type", "json");
                header.put("ver", VERSION);
                int i = this.seqId;
                this.seqId = i + 1;
                header.put("seqId", Integer.valueOf(i));
                object.put("header", header);
                ACObject payload = new ACObject();
                payload.put("className", table.getClassName());
                payload.put("primaryKey", table.getPrimaryKey());
                object.put("payload", payload);
                ACObject verifySign = new ACObject();
                ACSignature signature = new ACHelper().genSignature();
                verifySign.put(ClientCookie.DOMAIN_ATTR, AC.majorDomain);
                verifySign.put("userId", Long.valueOf(PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_USERID, 0)));
                verifySign.put("timestamp", Long.valueOf(signature.getTimestamp()));
                verifySign.put("timeout", Long.valueOf(signature.getTimeout()));
                verifySign.put("nonce", signature.getNonce());
                verifySign.put("sign", signature.getSignature());
                object.put("verifySign", verifySign);
                try {
                    this.client.send(ACObjectMarshaller.marshal(object));
                } catch (Exception e) {
                }
            }
            this.pushTables.clear();
        }
    }

    public void heartbeat() {
        LogUtil.d(TAG, "heartbeat");
        ACObject object = new ACObject();
        ACObject header = new ACObject();
        header.put("name", "heartbeat");
        header.put("type", "json");
        header.put("ver", VERSION);
        object.put("header", header);
        try {
            this.client.send(ACObjectMarshaller.marshal(object));
        } catch (Exception e) {
        }
    }

    @Override // com.accloud.service.ACPushMgr
    public void onReceive(PayloadCallback<ACPushReceive> callback) {
        this.receiver = callback;
    }

    @Override // com.accloud.service.ACPushMgr
    public void disconnect() {
        this.seqId = 0;
        this.pushTables.clear();
        this.watchCallbacks.clear();
        this.unwatchCallbacks.clear();
        this.receiver = null;
        this.disconnect = true;
        this.reConnect = false;
        if (this.isConnect) {
            AC.sEventManager.track(new DisconnectEvent(null));
        }
        this.isConnect = false;
        this.isReWatching = false;
        this.TIME = BufferRecycler.DEFAULT_WRITE_CONCAT_BUFFER_LEN;
        if (this.client != null) {
            this.client.close();
            this.client = null;
        }
        this.timestamp = 0;
    }

    @Override // com.accloud.service.ACPushMgr
    public void dispatchStatusEvent(StatusEvent statusEvent2) {
        this.statusEvent = statusEvent2;
    }

    /* access modifiers changed from: private */
    public class ConnectEvent extends ACEvent {
        private ConnectEvent() {
            super("apm_app_push_table", "connect", null);
        }
    }

    /* access modifiers changed from: private */
    public class DisconnectEvent extends ACEvent {
        private DisconnectEvent(ACException exception) {
            super("apm_app_push_table", "disconnect", exception);
        }
    }

    /* access modifiers changed from: private */
    public class WatchEvent extends ACEvent {
        private WatchEvent(ACPushTable table) {
            super("apm_app_push_table", "watch", null);
            try {
                this.data.put("class_name", table.getClassName());
                this.data.put("primary_keys", table.getPrimaryKey().toString());
                this.data.put("operation_type", ACPushTable.getOpDescription(table.getOpType()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class UnwatchEvent extends ACEvent {
        private UnwatchEvent(ACPushTable table) {
            super("apm_app_push_table", "unwatch", null);
            try {
                this.data.put("class_name", table.getClassName());
                this.data.put("primary_keys", table.getPrimaryKey().toString());
                this.data.put("operation_type", ACPushTable.getOpDescription(table.getOpType()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class ReceiveEvent extends ACEvent {
        private ReceiveEvent(String className, int opType, String payload) {
            super("apm_app_push_table", "recv", null);
            try {
                this.data.put("class_name", className);
                this.data.put("operation_type", ACPushTable.getOpDescription(opType));
                this.data.put("payload", payload);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
